package com.seezoon.application.user.executor;

import com.seezoon.application.user.dto.UserRegisterCmd;
import com.seezoon.domain.dao.po.UserInfoPO;
import com.seezoon.domain.service.user.UserRegisterService;
import com.seezoon.domain.service.user.vo.UserRegisterVO;
import com.seezoon.infrastructure.dto.Response;
import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.properties.AppProperties;
import com.seezoon.infrastructure.security.TotpService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * 用户注册
 */
@RequiredArgsConstructor
@Slf4j
@Component
@Validated
@Transactional
public class UserRegisterCmdExe {

    private final AppProperties appProperties;
    private final UserRegisterService userRegisterService;
    private final TotpService totpService;


    public Response execute(@Valid @NotNull UserRegisterCmd cmd) {
        // 检查验证码
        boolean verify = totpService.validateCode(
                (appProperties.getSecretKey() + cmd.getUsername()).getBytes(StandardCharsets.UTF_8),
                cmd.getCode());
        if (!verify && appProperties.getCodeValidateEnabled()) {
            return Response.error(ErrorCode.CODE_NOT_MATCH);
        }
        // 注册
        UserRegisterVO userRegisterVO = new UserRegisterVO();
        userRegisterVO.setRegisterType(cmd.getRegisterType());
        userRegisterVO.setUsername(cmd.getUsername());
        userRegisterVO.setPassword(cmd.getPassword());
        UserInfoPO userInfoPO = userRegisterService.register(userRegisterVO);
        log.info("user register success uid:{}", userInfoPO.getUid());
        return Response.success();
    }

}